#include "Cannon.h"
#define PI 3.14f
#define R_GUN 33
#include "Box.h"
#include "Sprite.h"
#include "ShareComponents.h"
#include "RSManager.h"
#include "BulletManager.h"
#include "Camera.h"

Cannon::Cannon(Box* box):Object(box,ObjEnemy_STATIC)
{
	_isShooting=false;
}


Cannon::~Cannon(void)
{
}



void Cannon::init()
{
	_sAppear=RSManager::getInstance()->getSprite(EMBUSHGUN_APPEAR);
	_sGun=RSManager::getInstance()->getSprite(EMBUSHGUN_GUN);	
	_angle=PI;
	gl_player=gl_player;
	delay=0;
	_shoottime=0;
	_isShooting = false;
	_isStop = false;
	_sprite = NULL;
	index = 0;
	_bulletCount =BULLET_COUNT;
	_hits=8;
	_isAlive=true;
	_obj= ObjEnemy_STATIC;
}
void Cannon::update()
{
	delay += GAME_TIME;
	
	if (abs(_box->_position.x - gl_player->_position.x) < 400)
	{
		if (_sprite == NULL)
		{
			_sprite = _sAppear;
		}
		else if (_sprite == _sAppear)
		{
			if (delay >300)
			{
				delay = 0;
				_sprite->Next();
			}
			if (_sprite->GetCurrentIndex() == 2)
				_sprite = _sGun;

		}

		else if (_sprite == _sGun)
		{
			_shoottime+=GAME_TIME;
			if (delay > 150)
			{
				delay = 0;
				_angle = SetAngle();
				if (_angle <=  PI+PI/10 &&_angle > PI/2 + 2*PI/5)
					index = 0;
				else if (_angle <= PI/2+ 2*PI/5 && _angle > PI/2 + PI/5)
					index = 1;
				else if (_angle <= PI/2 +PI/5 && _angle > PI / 2)
					index = 2;
				_sprite->Reset(index);
				if (_angle > PI / 2 && _angle <= PI+PI/12)
				{
					
					_isShooting = true;
					float gun_angle =abs(index-3)*(PI / 6) + PI / 2;
					D3DXVECTOR2 gun_direction(cosf(gun_angle)*R_GUN, sinf(gun_angle) * R_GUN-3);
					if(_shoottime>SHOOT_TIME)
					{
						_shoottime=0;
							if(_bulletCount>0)
							{
								_bulletCount--;
								BulletManager::getInstance()->shoot(B_E,_obj,_box->getCenterPos() + gun_direction,gun_angle);
							}
							else
							{
								_bulletCount--;
								if(_bulletCount<=-1)
									_bulletCount=BULLET_COUNT;
							}
					}
					
				}
				else
					_isShooting = false;	
			}
			//if(_hits<=0) _isAlive=false;
			_isAlive = _hits > 0;
		}
	}
	else
	{
		if (_sprite == _sGun)_sprite = _sAppear;
		if (_sprite)
		{
			if (delay > 300)
			{
				delay = 0;
				_sprite->Last();
			}
			//if (_sprite->GetCurrentIndex() == 0) _isStop = true;
			_isStop = _sprite->GetCurrentIndex() == 0;
		}
		_isShooting = false;
	}

	
}
float Cannon::SetAngle()
{
	float doi = gl_player->getCenterPos().y - _box->getCenterPos().y;
	float ke = gl_player->getCenterPos().x - _box->getCenterPos().x;

	return atan2(doi, ke)>0 ? atan2(doi, ke) : 2 * PI + atan2(doi, ke);
}
void Cannon::render()
{
	if (_sprite &&!_isStop && _isAlive)
		_sprite->Render(_box->_position);
}

Box* Cannon::getCollisionBox()
{
	_colBox->_position=_box->_position;
	_colBox->_size=_box->_size;
	_colBox->_v=_box->_v;
	return _colBox;
}
